//
//  UserListViewController.swift
//  demo
//
//  Created by 刘洪宝 on 2025/2/9.
//


import UIKit
class UserListViewController: UIViewController, UserListViewProtocol {
    
    var presenter: UserListPresenterProtocol?
    private let tableView = UITableView()
    private var users: [User] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        presenter?.viewDidLoad()
    }
    
    private func setupUI() {
        title = "用户列表"
        view.backgroundColor = .white
        
        tableView.frame = view.bounds
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UserCell")
        view.addSubview(tableView)
    }
    
    // MARK: - UserListViewProtocol
    func showUsers(_ users: [User]) {
        self.users = users
        tableView.reloadData()
    }
    
    func showLoading() {
        // 实现加载指示器
    }
    
    func hideLoading() {
        // 隐藏加载指示器
    }
    
    func showError(_ message: String) {
        let alert = UIAlertController(title: "错误", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}

extension UserListViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath)
        let user = users[indexPath.row]
        cell.textLabel?.text = user.name
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        presenter?.didSelectUser(users[indexPath.row])
    }
} 
